package com.example.wendao.view.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.common.PageUtils;
import com.example.wendao.databinding.ActivityPagingTestBinding;
import com.example.wendao.model.entity.User;
import com.example.wendao.view.adapter.HeaderProxyAdapter;
import com.example.wendao.view.adapter.UserListAdapter;
import com.example.wendao.viewmodel.UserViewModel;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class PagingTestActivity extends AppCompatActivity {

    private ActivityPagingTestBinding binding;
    UserListAdapter adapter = new UserListAdapter();
    UserViewModel userViewModel = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_paging_test);

        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        PageUtils.initRecyclerView(binding.rvTest, adapter, new LinearLayoutManager(this));

        userViewModel.getAllUser().observe(this, adapter::submitList);

        binds();

        binding.btnTest.setOnClickListener(v -> {
            userViewModel.addSomeUser(new User());
        });
    }

    private void binds() {
        // 模拟下拉刷新
        binding.srlTest.setOnRefreshListener(() -> {

            binding.srlTest.setRefreshing(true);
            Observable.just(0)
                    .delay(1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext(i -> {
                        binding.srlTest.setRefreshing(false);
                        adapter.submitList(null);
                        userViewModel.getAllUser().observe(this, users -> adapter.submitList(users));
                    }).subscribe();
        });
    }

}


